package com.ptszyxx.popose.module.main.dynamic;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.databinding.FragmentDynamicTabBinding;
import com.ptszyxx.popose.module.main.dynamic.adapter.DynamicAdapter;
import com.ptszyxx.popose.module.main.dynamic.vm.DynamicTabVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.dynamic.DynamicResult;
import com.ysg.utils.YStringUtil;

import java.util.List;

public class DynamicTabFragment extends BaseFragment<FragmentDynamicTabBinding, DynamicTabVM> {
    private DynamicAdapter adapter;
    private int tab;

    public DynamicTabFragment(){
    }

    public DynamicTabFragment(int tab){
        this.tab = tab;
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_dynamic_tab;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public DynamicTabVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(DynamicTabVM.class);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.tab = tab;
        viewModel.requestList(true);
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new DynamicAdapter(viewModel);
        binding.refreshView.initAdapter(adapter);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, o -> setAdapterData((List<DynamicResult>)o));
        viewModel.uc.onLikeEvent.observe(this, o -> onRefreshLike());
    }

    private void setAdapterData(List<DynamicResult> list) {
        binding.refreshView.setAdapterUI(adapter, list, viewModel.isRefresh());
    }

    /**
     * 刷新点赞
     */
    private void onRefreshLike() {
        DynamicResult item = viewModel.currentItem;
        try {
            if (YStringUtil.eq(1, item.getDzstate())){
                item.setDzstate(2);
                item.setGivenum((Integer.valueOf(item.getGivenum()) - 1) + "");
            }else{
                item.setDzstate(1);
                item.setGivenum((Integer.valueOf(item.getGivenum()) + 1) + "");
            }
        }catch (Exception e){
        }
        adapter.notifyItemChanged(viewModel.currentPosition);
    }
}
